const mongoose = require("mongoose");

// 获取商品数据
const getComm = async (rows) => {
  const commodityModel = mongoose.model("commodity");
  const seckillModel = mongoose.model("seckill");
  // 遍历获取到每个集合的商品数据
  // 遍历获取每个集合的秒杀商品数据
  for (let i = 0; i < rows.length; i++) {
    // console.log(data.rows[i]);commodities commodity_id
    for (let j = 0; j < rows[i].commodities.length; j++) {
      rows[i].commodities[j].commodity_id = await commodityModel.findOne({ _id: rows[i].commodities[j].commodity_id });
      rows[i].commodities[j].seckill_id = await seckillModel.findOne({ _id: rows[i].commodities[j].seckill_id });
    }
  }

  return rows;
}


// 获取订单当页数据
const get = async ({ curPage, eachPage }) => {
  (curPage = ~~curPage), (eachPage = ~~eachPage);

  let data = {
    total: 0
  }

  // 获取model对象
  const orderModel = mongoose.model('order');
  // 获取当前model映射的集合名存放文档总数 { isDisplay: 0 }表示没有被删除的数据
  data.total = await orderModel.countDocuments({ isDisplay: 0 });
  // 获取最大页  Math.ceil向上取整
  data.maxPage = Math.ceil(data.total / eachPage);

  // 计算跳过多少条
  const skipNum = (curPage - 1) * eachPage;
  // find是异步方法，populate(填充(找到相对应的完整数据返回))  skip(跳过多少条). limit(限制范围).exec=execute(执行)  sort({排序条件})
  // isDisplay: 0 为显示，1为不显示，但数据库数据依然存在
  data.rows = await orderModel.find({ isDisplay: 0 }).skip(skipNum).populate("userId").limit(eachPage).sort({ _id: -1 }).exec();
  data.rows = await getComm(data.rows);

  return data;
};

// 新增订单
const addOrder = async ({ commodities, isAffirmReceive, isPaySuccess, orderTime, totalPrice, userId, shoppingCartId, searchName, isDisplay }) => {



  // 获取用户购买的秒杀商品和秒杀商品数量
  // 在秒杀商品里更秒杀商品库存和已售
  const seckillModel = mongoose.model("seckill");
  for (let i = 0; i < commodities.length; i++) {
    const seckillData = await seckillModel.findOne({ _id: commodities[i].seckill_id, })
    // 判断购买数量是否小于库存
    if (commodities[i].count < seckillData.Total) {
      // 减去库存，增加已售
      seckillData.Total -= commodities[i].count;
      seckillData.Sold += commodities[i].count;
      await seckillModel.updateOne({ _id: seckillData._id }, seckillData);
    } else {
      return false;
    }
  }

  // 新增订单后，将新增到订单的商品从购物车删除
  const orderModel = mongoose.model('order');
  const data = await orderModel.create({ commodities, isAffirmReceive, isPaySuccess, orderTime, totalPrice, userId, searchName, isDisplay });

  // 有_id表示新增成功
  if (data._id) {
    const shoppingCartModel = mongoose.model("shoppingCart");
    for (let i = 0; i < shoppingCartId.length; i++) {
      await shoppingCartModel.remove({ _id: shoppingCartId[i] })
    }
    return data;
  }

};

// 删除订单
const delOrder = async (_id) => {
  const orderModel = mongoose.model('order');
  return await orderModel.updateOne({ _id }, { isDisplay: 1 });
};

// 通过商品名称查询订单
const findOrder = async ({ userId, searchName }) => {
  var info = {};
  var result = {};

  // 判断是否传入userId，
  // 如没传入，直接跳过搜索userId条件，
  // 如传入，则判断传入的userId是否有效，有效则添加userId查询条件，无效则返回对象 result["usersIdResult"] = "void";
  if (userId) {
    mongoose.isValidObjectId(userId) ? info.userId = userId : result["usersIdResult"] = "void";
  }

  // 需要将查询内容放在对象里面,需要多个查询对象时，在外层对象里添加对象即可
  // {searchName:{ $regex: name, $options: 'i' }}
  searchName ? info.searchName = { $regex: searchName, $options: 'i', } : "";

  info.isDisplay = 0;
  const orderModel = mongoose.model('order');
  const temp = await orderModel.find(info).populate("userId").exec();

  // 填充商品数据
  let rows = await getComm(temp);
  // 将返回的数据和判断userId值是否有效 合并并返回
  data = { rows, result };
  return data;
};


// 修改订单状态值
const changeState = async (_id) => {
  const orderModel = mongoose.model("order");
  return await orderModel.updateOne({ _id }, { isAffirmReceive: 1 });
};


// 根据订单id查询订单
const findOneOrderFromId = async (_id) => {
  const orderModel = mongoose.model("order");
  const temp = await orderModel.find({_id}).populate("userId").exec();

  // 填充商品数据
return await getComm(temp);
};
// 
// 根据订单id查询订单
const findOrderfromUserId = async (_id) => {
  const orderModel = mongoose.model("order");
  const temp = await orderModel.find({userId:_id}).populate("userId").sort({orderTime:-1}).exec();
  // 填充商品数据
return await getComm(temp);
};


module.exports = { get, addOrder, delOrder, findOrder, changeState,findOneOrderFromId,findOrderfromUserId};